package org.witsoft.demo.graphql.extend.directive;

import graphql.GraphqlErrorException;
import graphql.schema.*;
import graphql.schema.idl.SchemaDirectiveWiring;
import graphql.schema.idl.SchemaDirectiveWiringEnvironment;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatDirectiveWiring implements SchemaDirectiveWiring {

    @Override
    public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> env) {
        String format = (String) env.getDirective().getArgument("format").getValue();
        DataFetcher originalFetcher = env.getFieldDataFetcher();
        DataFetcher dataFetcher = DataFetcherFactories.wrapDataFetcher(originalFetcher, (fetch, value)->{
            if(value instanceof Date) {
                return new SimpleDateFormat(format).format((Date) value);
            }else{
                throw GraphqlErrorException.newErrorException()
                        .message("不支持的数据类型")
                        .build();
            }
        });
        GraphQLFieldDefinition field = env.getElement();
        GraphQLFieldsContainer parentType = env.getFieldsContainer();
        env.getCodeRegistry().dataFetcher(parentType, field, dataFetcher);
        return field;
    }
}
